package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.UserMapper;
import com.itheima.travel.pojo.User;
import com.itheima.travel.pojo.UserExample;
import com.itheima.travel.req.UserVo;
import com.itheima.travel.service.UserService;
import com.itheima.travel.session.SubjectUser;
import com.itheima.travel.session.SubjectUserContext;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @Description 用户服务类
 */
@Service
public class UserServiceImpl implements UserService {

    //注入dao层对象
    @Autowired
    private UserMapper userMapper;

    //处理用户的session工具
    @Autowired
    SubjectUserContext subjectUserContext;

    /**
     * 用户注册
     * @param userVo
     * @return
     */
    @Override
    public Boolean registerUser(UserVo userVo) {
        //对象转换vo--->pojo
        //BeanConv自己封装的的工具  底层依赖BeanUtils工具
        User user = BeanConv.toBean(userVo,User.class);
        // 对密码加密
        user.setPassword(MD5Coder.md5Encode(user.getPassword()));
        int flag = userMapper.insert(user);
        return flag>0;
    }

    /**
     *  登录
     * @param userVo
     * @return
     */
    @Override
    public UserVo loginUser(UserVo userVo) {
        //组装条件
        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andUsernameEqualTo(userVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(userVo.getPassword()));
        //查询list结果集
        List<User> users = userMapper.selectByExample(userExample);
        //转换VO
        List<UserVo> userVos = BeanConv.toBeanList(users, UserVo.class);
        //判断结果
        if (userVos.size()==1){
            UserVo userVoResult = userVos.get(0);
            //登录成功后将用户对象放入会话
            String token = UUID.randomUUID().toString();
            // 将token存放到响应结果对象中(为的是下一次请求时携带token,这样才能从session中获取对应的数据信息)
            userVoResult.setToken(token);
            // vo: 与web层的业务一一对应
            subjectUserContext.createdSubject(token,
                    BeanConv.toBean(userVoResult, SubjectUser.class));
            return userVoResult;
        }
        return null;
    }

    /**
     * 退出
     */
    @Override
    public void loginOutUser() {
        //从会话中删除当前对象
        subjectUserContext.deleteSubject();
    }

    /**
     * 判断是否有用户登录
     * @return
     */
    @Override
    public Boolean isLogin() {
        //根据当前用户是否存在判断登录状态
        return subjectUserContext.existSubject();
    }
}
